package com.sgb.kjwl.view.ui.activity.priceCheck;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;

import androidx.databinding.DataBindingUtil;

import android.os.Bundle;

import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import com.swgk.core.util.LogUtil;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityFindSupplierBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.pricecheck.SupplierEntitiy;
import com.sgb.kjwl.view.ui.adapter.pricecheck.FindSupplierAdapter;
import com.sgb.kjwl.viewmodel.self.prichcheck.FindSupplierModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 选择供应商
 *
 * @author Administrator
 */
public class FindSupplierActivity extends AppActivity implements FindSupplierAdapter.OnSupplierItemClickListener {

    private static final String TAG = "FindSupplierActivity";
    private ActivityFindSupplierBinding binding;
    private FindSupplierAdapter mFindSupplierAdapter;
    private List<SupplierEntitiy> findSupplierEntityList;
    private ArrayList<SupplierEntitiy> selectedSupplierList = new ArrayList<>();

    public static final String SUPPLIER_ENTITY = "supplier_entity";
    @Inject
    FindSupplierModel viewModel;
    private String searchSupplierName = "";

    public static void start(Context context) {
        start(context, null);
    }

    public static void start(Context context, Intent extras) {
        Intent intent = new Intent();
        intent.setClass(context, FindSupplierActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(FindSupplierActivity.this, R.layout.activity_find_supplier);
        binding.setViewModel(viewModel);
        setOnListener();
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().appComponent(appComponent).selfModule(new SelfModule(this)).build().inject(this);
    }

    private void setOnListener() {
        binding.backView.setOnClickListener(this);
        binding.commit.setOnClickListener(this);

        binding.searchSupplier.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        binding.searchSupplier.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                closeKeybord();
                searchSupplierName = binding.searchSupplier.getText().toString();
                viewModel.getSupplier(searchSupplierName);
            }
            return false;
        });
    }

    @Override
    protected void init() {
        initRecyclerView();
        viewModel.getSupplier(searchSupplierName);
    }

    private void initRecyclerView() {
        if (mFindSupplierAdapter == null) {
            mFindSupplierAdapter = new FindSupplierAdapter(getActivity(), findSupplierEntityList);
            mFindSupplierAdapter.setOnItemClickListener(this);
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setAdapter(mFindSupplierAdapter);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.getSupplier(searchSupplierName);
            }

            @Override
            public void onLoadMore() {
                viewModel.getSupplier(searchSupplierName);
            }
        });
    }

    public void fillSupplierList(List<SupplierEntitiy> supplierEntityList) {
        if (supplierEntityList == null || supplierEntityList.size() == 0) {
            LogUtil.d(TAG, "response is null or empty");
            return;
        }
        binding.recyclerView.setLoadingMoreEnabled(false);
        if (supplierEntityList.size() == 0) {
            LogUtil.d(TAG, "getPriceCheckList goodResourceList is null or empty");
            binding.recyclerView.refreshComplete();
            binding.emptyChild.emptyView.setVisibility(View.VISIBLE);
            return;
        }
        mFindSupplierAdapter.setDatas(supplierEntityList);
        binding.recyclerView.refreshComplete();
        binding.emptyChild.emptyView.setVisibility(supplierEntityList.size() == 0 ? View.VISIBLE : View.GONE);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_view:
                finish();
                break;
            case R.id.commit:
                Intent intent = new Intent();
                if (mFindSupplierAdapter != null) {
                    LogUtil.d(TAG, "setResult , campaniles is:" + selectedSupplierList.toString());

                    intent.putExtra(SUPPLIER_ENTITY, (Serializable) selectedSupplierList);
                    setResult(RESULT_OK, intent);
                    finish();
                }
                break;
            default:
                break;
        }
    }


    @SuppressLint("SetTextI18n")
    @Override
    public void onClickSupplierItem(SupplierEntitiy entity) {
        if (entity.isSelected()) {
            LogUtil.d(TAG, "onClickSupplierItem addEntity:" + entity.toString());
            /***
             *修复1.3.6版本的BUG 重复数据被选中后不再向集合中添加
             */
            if (!selectedSupplierList.contains(entity)) {
                selectedSupplierList.add(entity);
            }
        } else {
            if (selectedSupplierList.contains(entity)) {
                LogUtil.d(TAG, "onClickSupplierItem removeEntity:" + entity.toString());
                selectedSupplierList.remove(entity);
            }
            /**解决1.3.6 选中供应商后再刷新页面，再选中相同供应商后在取消选中，选中个数不改变的BUG***/
            SupplierEntitiy supplierEntitiy = copyEntity(entity);
            selectedSupplierList.remove(supplierEntitiy);
            /***解决1.3.6 选中供应商后再刷新页面，再选中相同供应商后在取消选中，选中个数不改变的BUG**/
        }
        int selectCount = selectedSupplierList.size();
        binding.commit.setText("确定(" + selectCount + ")");
        if (mFindSupplierAdapter != null) {
            mFindSupplierAdapter.setSelectCount(selectCount);
        }
    }

    /***
     *
     * @param supplierEntitiy
     * @return
     */
    private SupplierEntitiy copyEntity(SupplierEntitiy supplierEntitiy) {
        SupplierEntitiy entity = new SupplierEntitiy();
        entity.setCompanyAddress(supplierEntitiy.getCompanyAddress());
        entity.setSelected(true);
        entity.setFlag(supplierEntitiy.getFlag());
        entity.setMainBusiness(supplierEntitiy.getMainBusiness());
        entity.setName(supplierEntitiy.getName());
        entity.setPrivinceName(supplierEntitiy.getPrivinceName());
        entity.setNo(supplierEntitiy.getNo());
        entity.setProvinceNo(supplierEntitiy.getProvinceNo());
        return entity;
    }

}

